package com.financial.service.yspay.service.query.impl;

import com.alibaba.fastjson.JSON;
import com.financial.service.yspay.connector.SysconfigFeign;
import com.financial.service.yspay.constants.YsServiceEnumConstants;
import com.financial.service.yspay.dto.FinancialYsPayDTO;
import com.financial.service.yspay.service.FinancialYsPayBuildRequestParaService;
import com.financial.service.yspay.service.FinancialYsPayVerifyJsonSignService;
import com.financial.service.yspay.service.query.FinancialYsBalanceQueryService;
import com.financial.service.yspay.utils.DateUtils;
import com.financial.service.yspay.utils.HttpUtils;
import com.financial.service.yspay.utils.JsonUtils;
import com.financial.service.yspay.utils.apiresult.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author WANGNING
 * @Email wyn20140226@aliyun.com
 * @Description //银盛所有查询回执接口
 * @Date 2019/11/19 9:40
 */
@Service
public class FinancialYsBalanceQueryServiceImpl implements FinancialYsBalanceQueryService {
    private static final Logger logger = LoggerFactory.getLogger(FinancialYsBalanceQueryServiceImpl.class);

    @Value("${ysBalanceQueryMethod}")
    private String ysBalanceQueryMethod;

    @Autowired
    private FinancialYsPayBuildRequestParaService financialYsPayBuildRequestParaService;

    @Autowired
    private FinancialYsPayVerifyJsonSignService financialYsPayVerifyJsonSignService;

    @Autowired
    private SysconfigFeign sysconfigFeign;

    @Override
    public ApiResult balance(String requestParam) {
        logger.info("FinancialYsQueryServiceImpl.balance()---开始查询商户余额开始!");
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String ysPayAliPayJson = sysconfigFeign.getServiceYsConfig();
        FinancialYsPayDTO financialYsPayDTO = JsonUtils.parseObject(ysPayAliPayJson);
        Map<String, String> param = new HashMap<String, String>();
        /*银盛商户余额查询接口*/
        param.put("method", ysBalanceQueryMethod);
        param.put("partner_id", financialYsPayDTO.getPARTNER_ID());
        param.put("timestamp", DateUtils.getNowTimeStr());
        param.put("charset", financialYsPayDTO.getDEFAULT_CHARSET());
        param.put("sign_type", financialYsPayDTO.getSIGN_ALGORITHM());
        param.put("version", financialYsPayDTO.getVERSION());
        param.put("biz_content", requestParam);
        String content;
        try {
            /*签名*/
            Map<String, String> sPara = financialYsPayBuildRequestParaService.buildRequestPara(param, financialYsPayDTO);
            logger.error("FinancialYsQueryServiceImpl.balance()---银盛商户余额接口参数：" + sPara.toString());
            String returnString = HttpUtils.httpsSend(financialYsPayDTO.getYSEPAY_GATEWAY_URL_DSF(), sPara);
            logger.error("FinancialYsQueryServiceImpl.balance()---银盛商户余额接口返回数据：" + returnString);
            resultMap = (Map) JSON.parse(returnString);
            Object obj = resultMap.get("ysepay_merchant_balance_query_response");
            boolean verifyResult = false;
            if (obj == null) {
                return ApiResult.failure(JsonUtils.objectToJson("银盛返回结果为空"));
            }
            int ss = returnString.toString().indexOf("ysepay_merchant_balance_query_response");
            content = returnString.substring(ss);
            content = content.replace("ysepay_merchant_balance_query_response", "");
            content = content.substring(2, content.length() - 1);
            verifyResult = financialYsPayVerifyJsonSignService.verifyJsonSign(resultMap.get("sign").toString(), content, "utf-8", financialYsPayDTO);
            logger.error("FinancialYsQueryServiceImpl.balance()---验证签名信息" + verifyResult);
            logger.error("FinancialYsQueryServiceImpl.balance()---余额查询信息返回" + content);

            if (null == content || content.equals("")) {
                logger.info("FinancialYsQueryServiceImpl.balance()----->验签没有成功:银盛返回结果为空");
                return ApiResult.failure(JsonUtils.objectToJson("银盛返回结果为空"));
            }
            /*解析contrent*/
            Map<String, Object> contentMap = JsonUtils.jsonToMap(content);
            boolean codeState = contentMap.containsKey("code");
            logger.info("FinancialYsQueryServiceImpl.balance()----->余额查询结果状态:" + codeState);
            if (codeState) {
                Object tempParams = contentMap.get("code");
                String returnCode = tempParams == null ? null : tempParams.toString();
                if (returnCode.equalsIgnoreCase(YsServiceEnumConstants.ENUM_BALANCESTATUS_SUC)) {
                    /*10000是余额查询成功标识*/
                    return ApiResult.success(content);
                } else {
                    /*失败返回*/
                    return ApiResult.failure(content);
                }
            } else {
                /*失败返回*/
                return ApiResult.failure(content);
            }
        } catch (IOException e) {
            logger.error("FinancialYsQueryServiceImpl.balance()---银盛商户余额接口错误：" + e.getMessage());
            e.printStackTrace();
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
            logger.error("FinancialYsQueryServiceImpl.balance()---银盛商户余额接口错误：" + e1.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("FinancialYsQueryServiceImpl.balance()---银盛商户余额接口错误：" + e.getMessage());
        }
        return ApiResult.failure(requestParam);
    }
}
